// eslint-disable-next-line import/no-named-as-default
import { C36TabBarStandalone } from "@/components";
import { View } from "@tarojs/components";
import { useDeviceInfo } from "@/store/deviceContext";
import { Children, PropsWithChildren, useState } from "react";
import style from "./index.module.scss";
import { useApplicationInfo } from "@/store/applicationDataContext";
import { sendAction, ActionNames, ActionKeys } from "@/utils/tracking";

export type TabbedSectionProps = PropsWithChildren<{
  tabs: string[];
  type?: "default" | "discover";
}>;

function AbstractTabs({
  tabs,
  type = "default",
  children,
}: TabbedSectionProps) {
  const { applicationState, dispatch } = useApplicationInfo();
  const [activeTabIdx, setActiveTabIdx] = useState(0);
  const isDiscover = type === "discover";

  const onTabClick = (tabindex: number) => {
    sendAction(ActionNames.ExploreTopButtonClick, {[ActionKeys.CourseTopButtonName]: tabs[tabindex]});
    if (isDiscover) {
      dispatch({ type: "DISCOVER_TAB", data: { tab: tabindex } });
    } else {
      setActiveTabIdx(tabindex);
    }
  };

  // Children validation
  // (can't have typescript check react children types very easily)
  const childrenLength = Children.map(
    Children.toArray(children),
    (_, idx) => idx
  ).length;

  if (childrenLength !== tabs.length) {
    console.error("TabbedSection: Number of children and tabs not the same");
  }

  return (
    <View className={style["tabbed-section"]}>
      <View
        className={`
      ${style["tabbar-wrapper"]}
      ${style[`tabbar-wrapper-${type}`]}
      `}
        style={type === "discover" ? { top: 0 } : {}}
      >
        <C36TabBarStandalone
          tabs={tabs}
          type={type}
          activeTabIdx={
            isDiscover ? applicationState.selectedDiscoverTab : activeTabIdx
          }
          onTabClickCb={onTabClick}
        />
      </View>
      {Children.map(Children.toArray(children), (tabContent, idx) => {
        const activeTab = isDiscover
          ? applicationState.selectedDiscoverTab
          : activeTabIdx;
        if (idx === activeTab) {
          return (
            <View
              className={`${style["tab-content-wrapper"]} ${
                style[`tab-content-wrapper-${type}`]
              }`}
            >
              {tabContent}
            </View>
          );
        }
      })}
    </View>
  );
}

export default AbstractTabs;
